package demo.messaging.client.ui;

import com.allen_sauer.gwt.log.client.Log;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DockPanel;
import com.google.gwt.user.client.ui.TextBox;

import demo.messaging.client.core.ClientManager;
import demo.messaging.client.core.IMessageEventListener;
import demo.messaging.client.core.MessageEvent;
import demo.messaging.client.core.MessageEvent.EnumMessageEventType;
import demo.util_ui.client.ui.AbstractDialog;
import demo.util_ui.client.ui.UIFactory;

public class LoginUI extends AbstractDialog implements IMessageEventListener {

	final Button loginButton = new Button("Login");

	final TextBox loginField = new TextBox();

	public LoginUI() {

		this.loginField.setText("");

		//this.loginButton.addStyleName("sendButton");

		// Focus the cursor on the name field when the app loads
		this.loginField.setFocus(true);

		// Add a handler to send the name to the server
		this.loginButton.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(final ClickEvent event) {
				doLogin();
			}
		});

		// The Key up event is applied after the text has been changed. 
		this.loginField.addKeyUpHandler(new KeyUpHandler() {

			@Override
			public void onKeyUp(final KeyUpEvent event) {

				if (event.getNativeEvent().getKeyCode() == KeyCodes.KEY_ENTER) {
					doLogin();
				} else {
					updateButtonEnable();
				}
			}
		});

		setText("Login");

		getContentPanel().add(
				UIFactory.createLabel(
						"What name would you like to use for playing a game?",
						"message"), DockPanel.NORTH);

		getContentPanel().add(this.loginField, DockPanel.CENTER);

		getBottomPanel().add(this.loginButton, DockPanel.EAST);

		updateButtonEnable();

	}

	/**
	 * Send the name from the nameField to the server and wait for a response.
	 */
	private void doLogin() {
		// dialog.sendButton.setEnabled(false);

		String login = this.loginField.getText();
		ClientManager.getClientManager().login(login);

	}

	public String getLogin() {
		return this.loginField.getText();
	}

	@Override
	public void onMessageEvent(final MessageEvent event) {
		if (event.getType() == EnumMessageEventType.loginSuccess) {

			Log.debug("hiding LoginUI");
			ClientManager.getClientManager().setLogin(getLogin());
			this.removeFromParent();
		}

	}

	private void updateButtonEnable() {
		if (!this.loginField.getText().trim().isEmpty()) {
			this.loginButton.setEnabled(true);
		} else {
			this.loginButton.setEnabled(false);
		}
	}
}
